﻿using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfAdornerDemo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private bool _isAddornerAttached = false; //记录装饰器的数量

        public MainWindow()
        {
            InitializeComponent();
        }

        /// 通过点击按钮添加装饰器
        private void Border_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //1.获取装饰层
            var layer = AdornerLayer.GetAdornerLayer((UIElement)sender);

            if (layer != null && !_isAddornerAttached)
            {
                var adorner = new CustomAdorner((UIElement)sender);
                //2.添加装饰器
                layer.Add(adorner);
                _isAddornerAttached = true; //设置装饰器已添加
            }
        }

        /// 通过点击按钮移除装饰器
        private void Border_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            //1.获取装饰层
            var layer = AdornerLayer.GetAdornerLayer((UIElement)sender);

            //2.获取装饰器
            var adorners = layer.GetAdorners((UIElement)sender);

            if (adorners == null)
                return;

            //3.遍历移除装饰器
            foreach (var item in adorners)
            {
                layer.Remove(item);
                _isAddornerAttached = false;
            }
        }
    }
}